<template>
	<div class="collection">
    <van-search
        v-model="state.pageInfo.title"
        show-action
        @search="searchStore"
        @clear="clearSearchStore"
        placeholder="请输入门店名称关键词">
      <!-- 搜索框左图标 -->
      <template #action>
        <div @click="clickSearchStore">搜索</div>
      </template>
    </van-search>
		<van-list
			class="list"
			v-model:loading="state.loading"
			:finished="state.finished"
			finished-text="没有更多了"
      @load="getStoreTeamRecord"
		>
			<div class="list_item" v-for="item of state.collectRecord" :key="item.id">
				<van-image round width="45px" height="45px" fit="cover" :src="showHeadImgUrl(item)" />
				<div class="right">
					<div class="info">
						<div class="name">
							<span>{{ item.title }}</span>
							<img v-if="showVip(item)" class="vip" src="@/assets/img/vip_icon.png" />
							<img v-if="item.is_vip_video" class="certification" src="@/assets/img/certification_icon.png" />
						</div>
						<div class="address">{{ item.province }}-{{ item.city }}-{{ item.area }} 距离:{{ item.distance }}公里</div>
					</div>
          <van-radio :name="item.id" @click="selectStore(item.id)" v-model="state.pageInfo.store_id"></van-radio>
				</div>
			</div>
		</van-list>
	</div>

  <!-- 门店成交弹唱 -->
  <MyDialogBtn v-model:show="state.storeShow">
    <template #content>
      <div>确定选择当前门店支付么？</div>
    </template>
    <template #btn>
      <van-button type="primary" @click="closeWindow">再看看</van-button>
      <van-button type="success" @click="pay">立即支付</van-button>
    </template>
  </MyDialogBtn>
</template>

<script setup lang="ts">
import { reactive, onMounted } from 'vue';
import { useMainStore } from '@/store/index';
import { getVideoAuthStoreList } from '@/api/my';
import {createVipAuthOrder, updateUserLocation} from '@/api/index';
import { Toast } from 'vant';
import showVip from '@/hooks/showVip';
import {useRoute, useRouter} from "vue-router";
import {getWxConfig, wxVipAuthPay} from "@/api/common";
import wxApiReady from "@/hooks/wxApiReady";
import wx from "weixin-jsapi";
import MyDialogBtn from '@/components/MyDialogBtn.vue';

const imgUrl = import.meta.env.VITE_IMG_URL;
const route = useRoute();
const router = useRouter();
const mainStore = useMainStore();
const state = reactive<any>({
	loading: false,
	finished: false,
  storeShow: false,
  package_id:route.query.package_id,
  money:route.query.money,
	pageInfo: {
    title:'',
		pageIndex: 1,
		pageSize: 10,
		user_id: mainStore.user_id,
		store_id:0
	},
	collectRecord: []
});

onMounted( () => {
  getCurrentUserGps();
});

// 点击搜索
const clickSearchStore = (event:any) => {
  let keyword = state.pageInfo.title
  if (keyword) {
    state.pageInfo.pageIndex = 1;
    state.collectRecord = [];
    state.pageInfo.title = keyword;
    getStoreTeamRecord();
  }
}

// 搜索门店
const searchStore = (value:string) => {
  state.pageInfo.pageIndex = 1;
  state.collectRecord = [];
  state.pageInfo.title = value;
  getStoreTeamRecord();
}

// 清除搜索
const clearSearchStore = () => {
  state.pageInfo.pageIndex = 1;
  state.collectRecord = [];
  state.pageInfo.title = '';
  getStoreTeamRecord();
}

// 头像展示
const showHeadImgUrl = (item : any) => {
  if (item.storeimgs == null) {
    if (item.photo_list == '') {
      return item.user_info.head_img_url;
    } else {
      let photo_list = item.photo_list;
      let photo_list_arr = photo_list.split(',')
      return imgUrl + photo_list_arr[0];
    }
  } else {
    return imgUrl + item.storeimgs;
  }
}


// 关闭窗口
const closeWindow = () => {
  state.storeShow = false;
  state.pageInfo.store_id = 0;
}

// 选择门店
const selectStore = (store_id: number) => {
  let res = state.collectRecord
  let storeItem = null
  for (const key in res) {
    if (res[key].id == store_id) {
      storeItem = res[key];
    }
  }
  state.pageInfo.store_id = store_id
  state.storeShow = true;
}

// 立即支付
const pay = async () => {
  const res = await createVipAuthOrder(mainStore.user_id, state.money,state.package_id,1,state.pageInfo.store_id);
  Toast.loading({
    message: '加载中...',
    forbidClick: true,
  });
  const oid: number = res.data;
  const params: any = await wxVipAuthPay(oid);
  wxApiReady(['chooseWXPay'])
      .then((res) => {
        state.storeShow = false;
        wx.chooseWXPay({
          timestamp: params.timeStamp, // 支付签名时间戳，注意微信 jssdk 中的所有使用 timestamp 字段均为小写。但最新版的支付后台生成签名使用的 timeStamp 字段名需大写其中的 S 字符
          nonceStr: params.nonceStr, // 支付签名随机串，不长于 32 位
          package: params.package, // 统一支付接口返回的prepay_id参数值，提交格式如：prepay_id=\*\*\*）
          signType: params.signType, // 微信支付V3的传入 RSA ,微信支付V2的传入格式与V2统一下单的签名格式保持一致
          paySign: params.paySign, // 支付签名
          success: async (result: object) => {
            // 支付成功后的回调函数
            console.log(result);
            Toast.success('支付成功');
          }
        });
      })
      .catch((err) => console.log(err));
}

// 获取门店记录
const getStoreTeamRecord = async () => {
	const res = await getVideoAuthStoreList(state.pageInfo);
	let { dataList } = res.data;
	if (dataList.length) {
		state.pageInfo.pageIndex++;
		state.collectRecord = [...state.collectRecord, ...dataList];
		state.loading = false;
	} else {
		state.finished = true;
	}
}

// 定位城市获取列表
const getCurrentUserGps = async (): Promise<any> => {
  console.log('获取定位坐标');
  const configRes = await getWxConfig();
  const { appId, timestamp, nonceStr, signature } = configRes.data;
  let jsApiList = ['getLocation'];
  wx.config({
    debug: false,
    appId,
    timestamp,
    nonceStr,
    signature,
    jsApiList
  });
  wx.checkJsApi({
    jsApiList: ['getLocation'],
    success: (res:any) => {
      if (res.checkResult.getLocation == false) {
        console.log('你的微信版本太低，不支持微信JS接口，请升级到最新的微信版本！');
        return;
      }
    }
  });
  wx.ready(() => {
    wx.getLocation({
      type: 'wgs84',
      success: async (res: any) => {
        const { latitude, longitude } = res;
        const result = await updateUserLocation({
          id:mainStore.user_id,
          lat:latitude,
          lng:longitude
        });
        console.log(result)
      },
      fail: (res:any) => {
        console.info('ready getLocation fail=' + JSON.stringify(res))
      }
    });
  });
  wx.error((res:any) => {
    console.log('err', res)
  });
};
</script>

<style lang="scss" scoped>
:deep(.van-tabs) {
	width: 100%;
	.van-tabs__wrap {
		height: 55px !important;
		.van-tabs__nav {
			padding-left: 80px;
			padding-right: 80px;
			justify-content: space-between;
			.van-tab {
				flex: auto;
				padding: 0;
				font-size: 15px;
			}
			.van-tab--active {
				font-size: 16px;
				font-weight: bold;
			}
			.van-tabs__line {
				background: #f6438a;
			}
		}
	}
}
.collection {
	min-height: 100vh;
	background: #f5f5f5;
	.list {
		height: calc(100vh - 80px);
		overflow: scroll;
		padding: 10px 15px;
		.list_item {
			@include flx-justify-between;
			height: fit-content;
			box-sizing: border-box;
			padding: 15px;
			margin-bottom: 5px;
			border-radius: 5px;
			background: white;
			.right {
				@include flx-justify-between;
				height: 100%;
				flex: 1;
				margin-left: 10px;
				.info {
					.name {
						@include flx-align-center;
						margin-bottom: 5px;
						font-size: 16px;
						font-weight: bold;
						.vip {
							width: 16px;
							height: 14px;
							margin-left: 5px;
						}
						.certification {
							width: 54px;
							height: 20px;
							margin-left: 5px;
						}
					}
					.address {
						font-size: 12px;
						font-family: Noto Sans S Chinese;
						font-weight: 400;
						color: #808080;
					}
				}
				.delete {
					width: 13px;
					height: 15px;
				}
			}
		}
	}
}
</style>
